/*
 * Powered By XY
 * Since 2020
 */

package com.xy.biz.rs.service.impl;

import java.beans.Transient;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.xy.biz.base.client.DictClient;
import com.xy.biz.base.domain.req.ListDictItemRequest;
import com.xy.biz.base.domain.resp.ListDictItemResponse;
import com.xy.biz.fd.client.DocumentClient;
import com.xy.biz.fd.domain.req.document.CopyDocumentRequest;
import com.xy.biz.fd.domain.resp.GetDocumentResponse;
import com.xy.biz.rs.domain.constants.TechniqueConstants;
import com.xy.biz.rs.domain.converter.TechniqueConverter;
import com.xy.biz.rs.domain.query.ManufactureRecordTemplateQuery;
import com.xy.biz.rs.domain.req.SaveTechniqueRequest;
import com.xy.biz.rs.domain.req.UpdateTechniqueRequest;
import com.xy.biz.rs.domain.resp.GetTechniqueResponse;
import com.xy.biz.rs.manager.ManufactureRecordTemplateManager;
import com.xy.biz.rs.service.ManufactureRecordTemplateService;
import com.xy.tool.context.UserContextHolder;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xy.lang.domain.Result;
import com.xy.biz.rs.domain.bo.TechniqueBO;
import com.xy.biz.rs.domain.query.TechniqueQuery;
import com.xy.biz.rs.service.TechniqueService;
import com.xy.biz.rs.manager.TechniqueManager;
import org.springframework.util.CollectionUtils;

import javax.print.attribute.standard.RequestingUserName;

/**
 *
 *
 * @author wwj
 * @date 2021-4-13
 */
@Service
public class TechniqueServiceImpl implements TechniqueService {

	@Autowired
	private TechniqueManager techniqueManager;
	@Autowired
	private DictClient dictClient;

	@Autowired
	private DocumentClient documentClient;

	@Autowired
	private ManufactureRecordTemplateManager manufactureRecordTemplateManager;

	@Override
	public Result<?> saveTechnique(SaveTechniqueRequest request) {
		TechniqueBO techniqueBO = TechniqueConverter.toBO(request);
		int num = techniqueManager.countTechnique(
				TechniqueQuery.builder().productDictCode(techniqueBO.getProductDictCode())
						.subProductDictCode(techniqueBO.getSubProductDictCode()).build());
		if (num > 0) {
			return Result.ofConflict("此项目生产工艺已存在！");
		}
		buildBO(techniqueBO);
		int affectedRows = techniqueManager.saveTechnique(techniqueBO);
		if (affectedRows > 0) {
			return Result.success();
		}
		return Result.ofErrorRowsAffected();
	}

	private void buildBO(TechniqueBO techniqueBO) {
		techniqueBO.setStatus(TechniqueConstants.TECHNIQUE_STATUS_NOT_IN_USE);
		techniqueBO.setTenantId(UserContextHolder.getTenantId());
		techniqueBO.setCreateTime(LocalDateTime.now());
		techniqueBO.setUpdateTime(LocalDateTime.now());
		techniqueBO.setDeleteFlag(false);
	}

	@Override
	public Result<?> saveAllTechnique(Collection<TechniqueBO> collection) {
		int affectedRows = techniqueManager.saveAllTechnique(collection);
		if (affectedRows > 0) {
			return Result.success();
		}
		return Result.ofErrorRowsAffected();
	}

	@Transient
	@Override
	public Result<?> updateTechnique(UpdateTechniqueRequest request) {
		TechniqueBO techniqueBO = TechniqueConverter.toBO(request);
		techniqueBO.setUpdateTime(LocalDateTime.now());
		int affectedRows = techniqueManager.updateTechnique(techniqueBO);
		if (affectedRows > 0) {
			return Result.success();
		}
		return Result.ofErrorRowsAffected();
	}

	@Override
	public Result<?> deleteTechnique(Long techniqueId) {
		int affectedRows = techniqueManager.deleteTechnique(techniqueId);
		if (affectedRows > 0) {
			return Result.success();
		}
		return Result.ofErrorRowsAffected();
	}

	@Override
	public TechniqueBO getTechnique(Long techniqueId) {
		return techniqueManager.getTechnique(techniqueId);
	}

	@Override
	public List<TechniqueBO> listTechniqueById(Collection<Long> collection) {
		return techniqueManager.listTechniqueById(collection);
	}

	@Override
	public List<TechniqueBO> listTechnique(TechniqueQuery query) {
		List<TechniqueBO> techniqueBOS = techniqueManager.listTechnique(query);
        List<ListDictItemResponse> productDictItems = dictClient.listDictItem(ListDictItemRequest.builder().dictGroupCode("product").parentDictId(0L).build()).getData();
        Map<String, String> itemResponseMap = productDictItems.stream().collect(Collectors.toMap(ListDictItemResponse::getDictCode, v -> v.getDictValue()));
        for (TechniqueBO techniqueBO : techniqueBOS) {
            techniqueBO.setProductDictValue(itemResponseMap.get(techniqueBO.getProductDictCode()));
            techniqueBO.setSubProductDictValue(itemResponseMap.get(techniqueBO.getSubProductDictCode()));
        }
        return techniqueBOS;
	}

	@Override
	public int countTechnique(TechniqueQuery query) {
		return techniqueManager.countTechnique(query);
	}

	@Override
	public Result<GetTechniqueResponse> getByProductDictCode(TechniqueBO techniqueBO) {
		//同时验证一下数据表格
		int row = manufactureRecordTemplateManager.countManufactureRecordTemplate(ManufactureRecordTemplateQuery.builder()
				.status(1)
				.productDictCode(techniqueBO.getProductDictCode())
				.subProductDictCode(techniqueBO.getSubProductDictCode()).build());

		if (row == 0) {
			return Result.ofBadRequest("未查询到相关记录表单");
		}

		List<TechniqueBO> techniqueBOS = techniqueManager.listTechnique(TechniqueQuery.max()
				.status(1)
				.productDictCode(techniqueBO.getProductDictCode())
				.subProductDictCode(techniqueBO.getSubProductDictCode()).build());
		if (CollectionUtils.isEmpty(techniqueBOS)) {
			return Result.ofBadRequest("未查询到相关生产工艺");
		}

		return Result.success(TechniqueConverter.toResponse(techniqueBOS.get(0)));
	}

}
